﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.Security;
using Newtonsoft.Json;
using BSF.SystemConfig;

namespace BSF.Tool
{
    /// <summary>
    /// 模拟请求
    /// </summary>
    public class WebUrlHelper
    {
        #region 模拟请求(1)
        private static int _timeout = 100000;

        /// <summary>
        /// 请求与响应的超时时间
        /// </summary>
        public int Timeout
        {
            get { return _timeout; }
            set { _timeout = value; }
        }

        /// <summary>
        /// 获取GET请求结果，并转换为对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="url"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public static T DoGet<T>(string url, IDictionary<string, string> parameters = null)
        {
            string returnText = DoGet(url, parameters);

            //// 检查可能发生的错误
            //CheckIsErrorThenThrow(returnText);

            // 返回业务实体
            T result = JsonConvert.DeserializeObject<T>(returnText);

            return result;
        }

        /// <summary>
        /// 执行HTTP GET请求。
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="parameters">请求参数</param>
        /// <returns>HTTP响应</returns>
        public static string DoGet(string url, IDictionary<string, string> parameters)
        {
            if (parameters != null && parameters.Count > 0)
            {
                if (url.Contains("?"))
                {
                    url = url + "&" + BuildQuery(parameters);
                }
                else
                {
                    url = url + "?" + BuildQuery(parameters);
                }
            }


            WebClient wc = new WebClient();
            wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
            wc.Encoding = Encoding.UTF8;

            return wc.DownloadString(url);
        }

        /// <summary>
        /// 获取POST请求结果，并转换为对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="returnText"></param>
        /// <returns></returns>
        public static T DoPost<T>(string url, IDictionary<string, string> parameters = null)
        {
            string returnText = DoPost(url, parameters);

            //// 检查可能发生的错误
            //CheckIsErrorThenThrow(returnText);

            // 返回业务实体
            T result = JsonConvert.DeserializeObject<T>(returnText);

            return result;
        }

        /// <summary>
        /// 执行HTTP POST请求。
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="parameters">请求参数</param>
        /// <returns>HTTP响应</returns>
        public static string DoPost(string url, IDictionary<string, string> parameters)
        {
            HttpWebRequest req = GetWebRequest(url, "POST");
            req.ContentType = "application/x-www-form-urlencoded;charset=utf-8";

            byte[] postData = Encoding.UTF8.GetBytes(BuildQuery(parameters));
            System.IO.Stream reqStream = req.GetRequestStream();
            reqStream.Write(postData, 0, postData.Length);
            reqStream.Close();

            HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();
            //Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);
            Encoding encoding = string.IsNullOrEmpty(rsp.CharacterSet) ? Encoding.UTF8 : Encoding.GetEncoding(rsp.CharacterSet);
            return GetResponseAsString(rsp, encoding);
        }

        public static T DoPost<T>(string url, object data)
        {
            string returnText = DoPost(url, data);

            //// 检查可能发生的错误
            //CheckIsErrorThenThrow(returnText);

            // 返回业务实体
            T result = JsonConvert.DeserializeObject<T>(returnText);

            return result;
        }

        /// <summary>
        /// 执行HTTP POST请求。
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="parameters">请求参数</param>
        /// <returns>HTTP响应</returns>
        public static string DoPost(string url, object formData)
        {
            HttpWebRequest req = GetWebRequest(url, "POST");
            req.ContentType = "application/x-www-form-urlencoded;charset=utf-8";

            var jsonString = GetJsonString(formData);
            byte[] postData = Encoding.UTF8.GetBytes(jsonString);
            System.IO.Stream reqStream = req.GetRequestStream();
            reqStream.Write(postData, 0, postData.Length);
            reqStream.Close();

            HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();
            //Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);
            Encoding encoding = string.IsNullOrEmpty(rsp.CharacterSet) ? Encoding.UTF8 : Encoding.GetEncoding(rsp.CharacterSet);
            return GetResponseAsString(rsp, encoding);
        }

        /// <summary>
        /// 执行带文件上传的HTTP POST请求。
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="textParams">请求文本参数</param>
        /// <param name="fileParams">请求文件参数</param>
        /// <returns>HTTP响应</returns>
        public static string DoPost(string url, IDictionary<string, string> textParams, IDictionary<string, FileItem> fileParams)
        {
            // 如果没有文件参数，则走普通POST请求
            if (fileParams == null || fileParams.Count == 0)
            {
                return DoPost(url, textParams);
            }

            string boundary = DateTime.Now.Ticks.ToString("X"); // 随机分隔线

            HttpWebRequest req = GetWebRequest(url, "POST");
            req.ContentType = "multipart/form-data;charset=utf-8;boundary=" + boundary;

            System.IO.Stream reqStream = req.GetRequestStream();
            byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n");
            byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");

            // 组装文本请求参数
            string textTemplate = "Content-Disposition:form-data;name=\"{0}\"\r\nContent-Type:text/plain\r\n\r\n{1}";
            IEnumerator<KeyValuePair<string, string>> textEnum = textParams.GetEnumerator();
            while (textEnum.MoveNext())
            {
                string textEntry = string.Format(textTemplate, textEnum.Current.Key, textEnum.Current.Value);
                byte[] itemBytes = Encoding.UTF8.GetBytes(textEntry);
                reqStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
                reqStream.Write(itemBytes, 0, itemBytes.Length);
            }

            // 组装文件请求参数
            string fileTemplate = "Content-Disposition:form-data;name=\"{0}\";filename=\"{1}\"\r\nContent-Type:{2}\r\n\r\n";
            IEnumerator<KeyValuePair<string, FileItem>> fileEnum = fileParams.GetEnumerator();
            while (fileEnum.MoveNext())
            {
                string key = fileEnum.Current.Key;
                FileItem fileItem = fileEnum.Current.Value;
                string fileEntry = string.Format(fileTemplate, key, fileItem.GetFileName(), fileItem.GetMimeType());
                byte[] itemBytes = Encoding.UTF8.GetBytes(fileEntry);
                reqStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
                reqStream.Write(itemBytes, 0, itemBytes.Length);

                byte[] fileBytes = fileItem.GetContent();
                reqStream.Write(fileBytes, 0, fileBytes.Length);
            }

            reqStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
            reqStream.Close();

            HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();
            //Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);
            Encoding encoding = string.IsNullOrEmpty(rsp.CharacterSet) ? Encoding.UTF8 : Encoding.GetEncoding(rsp.CharacterSet);

            return GetResponseAsString(rsp, encoding);
        }

        public static HttpWebRequest GetWebRequest(string url, string method)
        {
            HttpWebRequest req = null;
            // todo:https
            //if (url.Contains("https"))
            //{
            //    ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            //    req = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url));
            //}
            //else
            //{
            //    req = (HttpWebRequest)WebRequest.Create(url);
            //}
            req = (HttpWebRequest)WebRequest.Create(url);

            // 修改http1.1协议存在的问题，当使用代理时如果不设置该项会返回417错误
            req.ServicePoint.Expect100Continue = false;
            req.Method = method;
            //req.KeepAlive = true;
            req.Timeout = _timeout;//this._timeout;

            return req;
        }

        /// <summary>
        /// 把响应流转换为文本。
        /// </summary>
        /// <param name="rsp">响应流对象</param>
        /// <param name="encoding">编码方式</param>
        /// <returns>响应文本</returns>
        public static string GetResponseAsString(HttpWebResponse rsp, Encoding encoding)
        {
            System.IO.Stream stream = null;
            StreamReader reader = null;

            try
            {
                // 以字符流的方式读取HTTP响应
                stream = rsp.GetResponseStream();
                reader = new StreamReader(stream, encoding);
                return reader.ReadToEnd();
            }
            finally
            {
                // 释放资源
                if (reader != null) reader.Close();
                if (stream != null) stream.Close();
                if (rsp != null) rsp.Close();
            }


        }

        /// <summary>
        /// 组装GET请求URL。
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="parameters">请求参数</param>
        /// <returns>带参数的GET请求URL</returns>
        public string BuildGetUrl(string url, IDictionary<string, string> parameters)
        {
            if (parameters != null && parameters.Count > 0)
            {
                if (url.Contains("?"))
                {
                    url = url + "&" + BuildQuery(parameters);
                }
                else
                {
                    url = url + "?" + BuildQuery(parameters);
                }
            }
            return url;
        }

        /// <summary>
        /// 组装普通文本请求参数。
        /// </summary>
        /// <param name="parameters">Key-Value形式请求参数字典</param>
        /// <returns>URL编码后的请求数据</returns>
        public static string BuildQuery(IDictionary<string, string> parameters)
        {
            StringBuilder postData = new StringBuilder();
            bool hasParam = false;

            IEnumerator<KeyValuePair<string, string>> dem = parameters.GetEnumerator();
            while (dem.MoveNext())
            {
                string name = dem.Current.Key;
                string value = dem.Current.Value;
                // 忽略参数名或参数值为空的参数
                if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(value))
                {
                    if (hasParam)
                    {
                        postData.Append("&");
                    }

                    postData.Append(name);
                    postData.Append("=");
                    postData.Append(HttpUtility.UrlEncode(value, Encoding.UTF8));
                    hasParam = true;
                }
            }

            return postData.ToString();
        }
        #endregion

        #region 模拟请求(2)
        #region 得到程序post过来的数据
        /// <summary>
        /// 得到程序post过来的数据
        /// </summary>
        /// <returns></returns>
        private string GetPostContent()
        {
            string postStr = string.Empty;
            //Stream inputStream = Request.InputStream;
            //int contentLength = Request.ContentLength;
            //int offset = 0;
            //if (contentLength > 0)
            //{
            //    byte[] buffer = new byte[contentLength];
            //    for (int i = inputStream.Read(buffer, offset, contentLength - offset); i > 0; i = inputStream.Read(buffer, offset, contentLength - offset))
            //    {
            //        offset += i;
            //    }
            //    UTF8Encoding encoding = new UTF8Encoding();
            //    postStr = encoding.GetString(buffer);
            //}
            return postStr;
        }
        #endregion
        /// <summary>
        /// 发送请求,向Url发送post请求
        /// </summary>
        /// <param name="postData">发送数据</param>
        /// <param name="uriStr">接受数据的Url</param>
        /// <returns>返回网站响应请求的回复</returns>
        public static string RequestPost(string postData, string uriStr)
        {
            HttpWebRequest requestScore = (HttpWebRequest)WebRequest.Create(uriStr);

            ASCIIEncoding encoding = new ASCIIEncoding();
            byte[] data = encoding.GetBytes(postData);
            requestScore.Method = "Post";
            requestScore.ContentType = "application/x-www-form-urlencoded";
            requestScore.ContentLength = data.Length;
            requestScore.KeepAlive = true;

            Stream stream = requestScore.GetRequestStream();
            stream.Write(data, 0, data.Length);
            stream.Close();

            HttpWebResponse responseSorce;
            try
            {
                responseSorce = (HttpWebResponse)requestScore.GetResponse();
            }
            catch (WebException ex)
            {
                responseSorce = (HttpWebResponse)ex.Response;//得到请求网站的详细错误提示
            }
            StreamReader reader = new StreamReader(responseSorce.GetResponseStream(), Encoding.UTF8);
            string content = reader.ReadToEnd();

            requestScore.Abort();
            responseSorce.Close();
            responseSorce.Close();
            reader.Dispose();
            stream.Dispose();
            return content;
        }
        public string SendRequest(string url, string strRequst, string Method)
        {
            if (Method == "POST")
            {
                ASCIIEncoding encoding = new ASCIIEncoding();
                byte[] data = encoding.GetBytes(strRequst);
                HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);
                myRequest.Method = "POST";
                myRequest.ContentType = "application/x-www-form-urlencoded";
                myRequest.ContentLength = data.Length;
                Stream newStream = myRequest.GetRequestStream();
                newStream.Write(data, 0, data.Length);
                newStream.Close();
                HttpWebResponse myResponse;
                try
                {
                    myResponse = (HttpWebResponse)myRequest.GetResponse();
                }
                catch (WebException ex)
                {
                    myResponse = (HttpWebResponse)ex.Response;//得到请求网站的详细错误提示
                }
                StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);//java编码格式
                //StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.Default);
                string result = reader.ReadToEnd();
                result = result.Replace("/r", "").Replace("/n", "").Replace("/t", "");
                int status = (int)myResponse.StatusCode;
                reader.Close();
                return result;
            }
            else if (Method == "GET")
            {
                if (string.IsNullOrEmpty(url))
                    return "false";
                HttpWebRequest httpRequest;
                if (string.IsNullOrEmpty(strRequst))
                    httpRequest = (HttpWebRequest)WebRequest.Create(url);
                else if (!string.IsNullOrEmpty(strRequst) && url.IndexOf("?") > 0)
                    httpRequest = (HttpWebRequest)WebRequest.Create(url + "&" + strRequst);
                else
                    httpRequest = (HttpWebRequest)WebRequest.Create(url + "?" + strRequst);
                //HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(url + "?" + strRequst);
                //HttpRequest.Timeout = 2000;
                httpRequest.Method = "GET";
                HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse();
                StreamReader sr = new StreamReader(httpResponse.GetResponseStream(), System.Text.Encoding.GetEncoding("utf-8"));
                string result = sr.ReadToEnd();
                result = result.Replace("/r", "").Replace("/n", "").Replace("/t", "");
                int status = (int)httpResponse.StatusCode;
                sr.Close();
                return result;//失败：[{filename:'96f5affa-5195-4272-973b-e71c27008430.jpg',ret:-1,msg:'nofile'}]，成功：[{filename:'96f5affa-5195-4272-973b-e71c27008430.jpg',ret:0}]
            }
            return "";
        }
        public static string SendRequest(string url, string strRequst, string Method, Encoding encode)
        {
            if (Method == "POST")
            {
                ASCIIEncoding encoding = new ASCIIEncoding();
                byte[] data = encoding.GetBytes(strRequst);
                HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);
                myRequest.Method = "POST";
                myRequest.ContentType = "application/x-www-form-urlencoded";
                myRequest.ContentLength = data.Length;
                Stream newStream = myRequest.GetRequestStream();
                newStream.Write(data, 0, data.Length);
                newStream.Close();
                HttpWebResponse myResponse;
                try
                {
                    myResponse = (HttpWebResponse)myRequest.GetResponse();
                }
                catch (WebException ex)
                {
                    myResponse = (HttpWebResponse)ex.Response;//得到请求网站的详细错误提示
                }
                StreamReader reader = new StreamReader(myResponse.GetResponseStream(), encode);
                string result = reader.ReadToEnd();
                result = result.Replace("/r", "").Replace("/n", "").Replace("/t", "");
                int status = (int)myResponse.StatusCode;
                reader.Close();
                return result;
            }
            else if (Method == "GET")
            {
                if (string.IsNullOrEmpty(url))
                    return "false";
                HttpWebRequest httpRequest;
                if (string.IsNullOrEmpty(strRequst))
                    httpRequest = (HttpWebRequest)WebRequest.Create(url);
                else if (!string.IsNullOrEmpty(strRequst) && url.IndexOf("?") > 0)
                    httpRequest = (HttpWebRequest)WebRequest.Create(url + "&" + strRequst);
                else
                    httpRequest = (HttpWebRequest)WebRequest.Create(url + "?" + strRequst);
                //HttpRequest.Timeout = 2000;
                httpRequest.Method = "GET";
                HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse();
                StreamReader sr = new StreamReader(httpResponse.GetResponseStream(), encode);
                string result = sr.ReadToEnd();
                result = result.Replace("/r", "").Replace("/n", "").Replace("/t", "");
                int status = (int)httpResponse.StatusCode;
                sr.Close();
                return result;
            }
            return "";
        }
        public static string SendRequest(string url, string strRequst, string Method, WebProxy proxy)
        {
            if (Method == "POST")
            {
                ASCIIEncoding encoding = new ASCIIEncoding();
                byte[] data = encoding.GetBytes(strRequst);
                HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);
                myRequest.Method = "POST";
                myRequest.ContentType = "application/x-www-form-urlencoded";
                myRequest.ContentLength = data.Length;
                Stream newStream = myRequest.GetRequestStream();
                newStream.Write(data, 0, data.Length);
                newStream.Close();
                HttpWebResponse myResponse;
                try
                {
                    myResponse = (HttpWebResponse)myRequest.GetResponse();
                }
                catch (WebException ex)
                {
                    myResponse = (HttpWebResponse)ex.Response;//得到请求网站的详细错误提示
                }
                StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);//java编码格式
                //StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.Default);
                string result = reader.ReadToEnd();
                result = result.Replace("/r", "").Replace("/n", "").Replace("/t", "");
                int status = (int)myResponse.StatusCode;
                reader.Close();
                return result;
            }
            else if (Method == "GET")
            {
                if (string.IsNullOrEmpty(url))
                    return "false";
                HttpWebRequest httpRequest;
                if (string.IsNullOrEmpty(strRequst))
                    httpRequest = (HttpWebRequest)WebRequest.Create(url);
                else if (!string.IsNullOrEmpty(strRequst) && url.IndexOf("?") > 0)
                    httpRequest = (HttpWebRequest)WebRequest.Create(url + "&" + strRequst);
                else
                    httpRequest = (HttpWebRequest)WebRequest.Create(url + "?" + strRequst);
                //HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(url + "?" + strRequst);
                httpRequest.Proxy = proxy;
                httpRequest.Timeout = 2000;
                httpRequest.Method = "GET";
                HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse();
                StreamReader sr = new StreamReader(httpResponse.GetResponseStream(), System.Text.Encoding.GetEncoding("utf-8"));
                string result = sr.ReadToEnd();
                result = result.Replace("/r", "").Replace("/n", "").Replace("/t", "");
                int status = (int)httpResponse.StatusCode;
                sr.Close();
                httpResponse.Close();
                return result;//失败：[{filename:'96f5affa-5195-4272-973b-e71c27008430.jpg',ret:-1,msg:'nofile'}]，成功：[{filename:'96f5affa-5195-4272-973b-e71c27008430.jpg',ret:0}]
            }
            return "";
        }
        private void SaveTouxiang(string userID, string type, string UploadHeadFilePath, string imgPath, string photoSize = "0", string photoWidth = "0", string photoHeight = "0")
        {
            //现在的头像是先上传到服务器上,然后在上传到存储图片的MongoDB库
            //先传到服务器上的临时地址
            //UploadHeadFilePath = UnityHelper.GetValue(UploadHeadFilePath, @"D:\Inetpub\wwwroot\fileupload\tempfiles\");
            //imgPath = UnityHelper.GetValue(imgPath, string.Format("{0}/{1}.jpg", DateTime.Now.ToString("yyyyMM"), userID));
            string imgname = DateTime.Now.ToString("yyyyMM") + userID + ".jpg";
            //图片存储接口调用
            string sign = FormsAuthentication.HashPasswordForStoringInConfigFile(string.Format("{0}{1}", "sefs-583tdf3-es54", userID), "MD5");

            ArrayList keylist = new ArrayList();
            ArrayList valuelist = new ArrayList();
            keylist.Insert(0, "userid");
            keylist.Insert(1, "uploadTypeID");
            keylist.Insert(2, "crystr");
            keylist.Insert(3, "applicationid");
            keylist.Insert(4, "Filename");
            keylist.Insert(5, "id");

            valuelist.Insert(0, userID);
            valuelist.Insert(1, "14");
            valuelist.Insert(2, sign);
            valuelist.Insert(3, "12");
            valuelist.Insert(4, UploadHeadFilePath + imgname);
            valuelist.Insert(5, userID);

            string ret = POSTfile(UploadHeadFilePath + imgPath, keylist, valuelist);
        }
        public string POSTfile(string fileName, ArrayList keylist, ArrayList valuelist)
        {
            string boundary = "-----------" + DateTime.Now.Ticks.ToString("x");
            //请求 
            WebRequest req = WebRequest.Create("http://upload01.img.baomihua.com/uploadimg.aspx");
            req.ContentType = "multipart/form-data; boundary=" + boundary;
            req.Method = "POST";
            //组织表单数据 
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < keylist.Count; i++)
            {
                sb.Append("--" + boundary);
                sb.Append("\r\n");
                sb.Append("Content-Disposition: form-data; name=\"" + keylist[i] + "\"");

                sb.Append("\r\n");
                sb.Append("\r\n");
                sb.Append(valuelist[i]);//value前面必须有2个换行
                sb.Append("\r\n");
            }
            //拼接文件控件
            sb.Append("--" + boundary);
            sb.Append("\r\n");
            sb.Append(string.Format("Content-Disposition: form-data; name=\"Filedata\"; filename=\"{0}\"", fileName));
            sb.Append("\r\n");
            sb.Append("Content-Type: application/octet-stream");
            sb.Append("\r\n");
            sb.Append("\r\n");
            string head = sb.ToString();
            byte[] form_data = Encoding.UTF8.GetBytes(head);
            //结尾 
            byte[] foot_data = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n");
            //文件 
            FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
            //post总长度 
            long length = form_data.Length + fileStream.Length + foot_data.Length;
            req.ContentLength = length;
            Stream requestStream = req.GetRequestStream();
            //发送表单参数 
            requestStream.Write(form_data, 0, form_data.Length);
            //文件内容 
            byte[] buffer = new Byte[checked((uint)Math.Min(4096, (int)fileStream.Length))];
            int bytesRead = 0;
            while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                requestStream.Write(buffer, 0, bytesRead);
            //结尾 
            requestStream.Write(foot_data, 0, foot_data.Length);
            requestStream.Close();
            //响应
            WebResponse pos = req.GetResponse();
            StreamReader sr = new StreamReader(pos.GetResponseStream(), Encoding.UTF8);
            string html = sr.ReadToEnd().Trim();
            sr.Close();
            if (pos != null)
            {
                pos.Close();
                pos = null;
            }
            if (req != null)
            {
                req = null;
            }
            return html;
        }
        public string POSTfile(string fileName, Dictionary<string, string> inputDic)
        {
            try
            {
                //string sReg = @"\.jpg|\.jpeg|\.png";
                //if (!Regex.IsMatch(fileName, sReg, RegexOptions.IgnoreCase))
                //{
                //    Console.WriteLine("只接受jpg或png格式图片");
                //    return "";
                //}
                string boundary = "-----------" + DateTime.Now.Ticks.ToString("x");
                //请求 
                WebRequest req = WebRequest.Create("http://upload01.img.baomihua.com/uploadimg.aspx");
                req.ContentType = "multipart/form-data; boundary=" + boundary;
                req.Method = "POST";
                //组织表单数据 
                StringBuilder sb = new StringBuilder();
                foreach (KeyValuePair<string, string> dicItem in inputDic)
                {
                    sb.Append("--" + boundary);
                    sb.Append("\r\n");
                    sb.Append("Content-Disposition: form-data; name=\"" + dicItem.Key + "\"");
                    sb.Append("\r\n");
                    sb.Append("\r\n");
                    sb.Append(dicItem.Value);//value前面必须有2个换行
                    sb.Append("\r\n");
                }
                //拼接文件控件
                sb.Append("--" + boundary);
                sb.Append("\r\n");
                //sb.Append("Content-Disposition: form-data; name=\"Filedata\"; filename=\"1e4c9eb5a6a1059f37d3ca70[1].jpg\"");
                string[] filenames = fileName.Trim().Replace(" ", "").Split('\\');
                sb.Append("Content-Disposition: form-data; name=\"Filedata\"; filename=\"" + filenames[filenames.Length - 1] + "\"");
                sb.Append("\r\n");
                sb.Append("Content-Type: application/octet-stream");
                sb.Append("\r\n");
                sb.Append("\r\n");
                string head = sb.ToString();
                byte[] form_data = Encoding.UTF8.GetBytes(head);
                //结尾 
                byte[] foot_data = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n");
                //文件 
                FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
                //post总长度 
                long length = form_data.Length + fileStream.Length + foot_data.Length;
                req.ContentLength = length;
                Stream requestStream = req.GetRequestStream();
                //发送表单参数 
                requestStream.Write(form_data, 0, form_data.Length);
                //文件内容 
                byte[] buffer = new Byte[checked((uint)Math.Min(4096, (int)fileStream.Length))];
                int bytesRead = 0;
                while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                    requestStream.Write(buffer, 0, bytesRead);
                //结尾 
                requestStream.Write(foot_data, 0, foot_data.Length);
                requestStream.Close();
                //响应
                WebResponse pos = req.GetResponse();
                StreamReader sr = new StreamReader(pos.GetResponseStream(), Encoding.UTF8);
                string html = sr.ReadToEnd().Trim();
                sr.Close();
                if (pos != null)
                {
                    pos.Close();
                    pos = null;
                }
                if (req != null)
                {
                    req = null;
                }
                return html;
            }
            catch (Exception e)
            {
                //Debug.WriteLine(String.Format("[PMH.Managerv3][PMHAuditUsers][DAL:DownLoad]:time={0},异常信息:{1}", DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss fff"), e.Message));
                Trace.Write(String.Format("[PMH.Managerv3][PMHAuditUsers][DAL:POSTfile]:time={0},异常信息:{1}", DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss fff"), e.Message));//用于测试查看
                return string.Empty;
            }
        }
        #endregion

        #region 模拟请求(3)
        /// <summary>
        /// 获取指定地址的html
        /// </summary>
        /// <param name="URL"></param>
        /// <param name="PostData"></param>
        /// <param name="encoding"></param>
        /// <returns></returns>
        public static string GetHTML(string URL, string RequestMode, string PostData, System.Text.Encoding encoding)
        {
            bool isKeepAlive = false;
            string _Html = "";
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL);
            request.Accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-excel, application/msword, application/x-shockwave-flash, */*";

            //if (_Cookies.Count > 0)
            //{
            //    request.CookieContainer.Add(new Uri(URL), _Cookies);
            //}
            //else
            //{
            //    request.CookieContainer = this.cookieContainer;
            //}

            //提交的数据
            if (PostData != null && PostData.Length > 0)
            {
                request.ContentType = "application/x-www-form-urlencoded";
                request.Method = RequestMode;

                byte[] b = encoding.GetBytes(PostData);
                request.ContentLength = b.Length;
                using (System.IO.Stream sw = request.GetRequestStream())
                {
                    try
                    {
                        sw.Write(b, 0, b.Length);
                    }
                    catch (Exception ex)
                    {
                        throw new Exception("Post Data Error!!", ex);
                    }
                    finally
                    {
                        if (sw != null) { sw.Close(); }
                    }
                }
            }

            HttpWebResponse response = null;
            System.IO.StreamReader sr = null;
            try
            {
                response = (HttpWebResponse)request.GetResponse();
                //_Cookies = response.Cookies;
                sr = new System.IO.StreamReader(response.GetResponseStream(), encoding);
                _Html = sr.ReadToEnd();
            }
            catch (WebException webex)
            {
                if (webex.Status == WebExceptionStatus.KeepAliveFailure)
                {
                    isKeepAlive = true;
                }
                else
                {
                    throw new Exception("DownLoad Data Error", webex);
                }
            }
            catch (System.Exception ex)
            {
                throw new Exception("DownLoad Data Error", ex);
            }
            finally
            {
                if (sr != null) { sr.Close(); }
                if (response != null) { response.Close(); }
                response = null;
                request = null;
            }
            return _Html;
        }
        /// <summary>
        /// C#模拟http 发送post或get请求
        /// 向指定URL发送POST请求
        /// </summary>
        /// <param name="Url">URL地址</param>
        /// <param name="postDataStr"></param>
        /// <returns></returns>
        public static string HttpPost(string Url, string postDataStr)
        {
            String sResult = "";
            if (Url == "" || postDataStr == "")
            {
                return sResult;
            }
            try
            {
                //准备发送请求
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                //request.ContentType = "application/json; encoding=utf-8";
                request.ContentLength = System.Text.Encoding.UTF8.GetByteCount(postDataStr);//计算对指定的 System.String 中的字符进行编码时所产生的字节数//request.ContentLength = postDataStr.Length;
                //request.CookieContainer = cookie;
                System.IO.Stream myRequestStream = request.GetRequestStream();
                //发送数据
                Encoding encoding = System.Text.Encoding.GetEncoding("utf-8");//ASCIIEncoding encoding = new ASCIIEncoding();
                byte[] bufferdata = encoding.GetBytes(postDataStr);//编码，尤其是汉字，事先要看下抓取网页的编码方式
                myRequestStream.Write(bufferdata, 0, bufferdata.Length);
                myRequestStream.Close();
                //异常：1.写入流的字节超出指定的 Content-Length 字节大小。2.请求被中止: 请求已被取消。原因是添加了 contentLength，注释掉request.ContentLength = data.Length;就好了
                //StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("utf-8"));
                //myStreamWriter.Write(postDataStr);
                //myStreamWriter.Close();
                //获取返回数据
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                //response.Cookies = cookie.GetCookies(response.ResponseUri);
                Stream myResponseStream = response.GetResponseStream();
                StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("gb2312"));
                sResult = myStreamReader.ReadToEnd();
                sResult.Trim();
                myStreamReader.Close();
                myResponseStream.Close();
            }
            catch (Exception ex)
            {
                sResult = ex.Message;
                return sResult;
            }
            return sResult;
        }
        /// <summary>
        /// C#模拟http 发送post或get请求
        /// </summary>
        /// <param name="Url"></param>
        /// <param name="postDataStr"></param>
        /// <returns></returns>
        public static string HttpGet(string Url, string postDataStr)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (postDataStr == "" ? "" : "?") + postDataStr);
            request.Method = "GET";
            request.Timeout = 20 * 1000;
            request.ContentType = "text/html;charset=UTF-8";

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();

            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();
            return retString;
        }
        /// <summary>
        /// C#模拟http 发送post或get请求
        /// </summary>
        /// <param name="Url"></param>
        /// <param name="postDataStr"></param>
        /// <returns></returns>
        public static string HttpGetImg(string Url, string postDataStr)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (postDataStr == "" ? "" : "?") + postDataStr);
            request.Method = "GET";
            request.Timeout = 20 * 1000;
            request.ContentType = "text/html;charset=UTF-8";

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();

            //转byte[]然后在转成image 有异常
            //byte[] arrbyte = ConvertHelper.converter.StreamToBytes(myResponseStream);
            //string retString = ConvertHelper.converter.CreateImageFromBytes(arrbyte, @"c:\a.jpg");
            //ConvertHelper.converter.StreamToFile(myResponseStream, @"c:\b.jpg");
            #region 保存图片
            string retString = string.Empty;
            //Stream _stream = ConvertHelper.converter.getYCStream("http://himg2.huanqiu.com/attachment/081104/55c7e57181.jpg");
            //根目录路径，相对路径
            String rootPath = BSFConfig.QRImage + DirectoryHelper.CreateFilePath() + "/";
            String dirPath = System.Web.HttpContext.Current.Server.MapPath(rootPath);
            string filename = DirectoryHelper.CreateFileName() + ".jpg";
            DirectoryHelper.CreateDirectory(dirPath);

            Dictionary<string, string> dict = new Dictionary<string, string>();
            dict.Add("dirpath", dirPath);
            dict.Add("filename", filename);
            dict.Add("relativepath", rootPath + filename);
            SaveYCStream(myResponseStream, dict);
            retString = dict["relativepath"].ToString();
            #endregion

            //StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            //retString = myStreamReader.ReadToEnd();
            //myStreamReader.Close();
            //myResponseStream.Close();
            return retString;
        }
        #endregion


        #region asp.net(c#)判断远程图片是否存在
        private int GetUrlError(string curl)
        {
            #region ASP.net页面中请求远程Web站点
            //有朋友问到，如何在已有ASP.net页面中，去请求远程WEB站点，并能传参，且得到请求所响应的结果。用下边的小例子讲解具体功能的实现：
            //首先，我们想要请求远程站点，需要用到HttpWebRequest类，该类在System.Net命名空间中，所以需要引用一下。另外，在向请求的页面写入参数时需要用到Stream流操作，所以需要引用System.IO命名空间。
            //以下为Get请求方式：
            //Uri uri = new Uri("http://www.cnsaiko.com/");//创建uri对象，指定要请求到的地址  
            //if (uri.Scheme.Equals(Uri.UriSchemeHttp))//验证uri是否以http协议访问
            //{  
            //    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);//使用HttpWebRequest类的Create方法创建一个请求到uri的对象。
            //    request.Method = WebRequestMethods.Http.Get;//指定请求的方式为Get方式

            //    HttpWebResponse response = (HttpWebResponse)request.GetResponse();//获取该请求所响应回来的资源，并强转为HttpWebResponse响应对象
            //    StreamReader reader = new StreamReader(response.GetResponseStream());//获取该响应对象的可读流

            //    string str = reader.ReadToEnd(); //将流文本读取完成并赋值给str
            //    response.Close(); //关闭响应
            //    Response.Write(str); //本页面输出得到的文本内容
            //    Response.End(); //本页面响应结束。
            //} 

            //以下为POST请求方式：
            //Uri uri = new Uri("http://www.cnsaiko.com/Admin/Login.aspx?type=Login");//创建uri对象，指定要请求到的地址，注意请求的地址为form表单的action地址。  
            //if (uri.Scheme == Uri.UriSchemeHttp)//验证uri是否以http协议访问
            //{
            //    string name = Server.UrlEncode("张三");//将要传的参数进行url编码
            //    string pwd = Server.UrlEncode("123");
            //    string data = "UserName=" + name + "&UserPwd=" + pwd; //data为要传的参数，=号前边的为表单元素的名称，后边的为要赋的值；如果参数为多个，则使用"&"连接。
            //    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
            //    request.Method = WebRequestMethods.Http.Post;//指定请求的方式为Post方式
            //    request.ContentLength = data.Length; //指定要请求参数的长度
            //    request.ContentType = "application/x-www-form-urlencoded"; //指定请求的内容类型

            //    StreamWriter writer = new StreamWriter(request.GetRequestStream()); //用请求对象创建请求的写入流
            //    writer.Write(data); //将请求的参数列表写入到请求对象中
            //    writer.Close(); //关闭写入流。

            //    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            //    StreamReader reader = new StreamReader(response.GetResponseStream());

            //    string str = reader.ReadToEnd();
            //    response.Close();
            //    Response.Write(str);
            //    Response.End();
            //}
            #endregion
            //int num = 200;
            //if (this.method == 1) 
            int num = 1;
            if (curl.Length > 1)
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(curl));
                ServicePointManager.Expect100Continue = false;
                try
                {
                    //图片不存在返回{ ret:-1,msg:'failed'}  Content-Type	text/html; charset=utf-8
                    string a = request.GetResponse().ContentType;//图片-image/jpeg  文字-text/html; charset=utf-8
                    if (a.Trim().Replace(" ", "").Equals("text/html;charset=utf-8"))//if (!a.Equals("image/jpeg"))
                    {
                        num = 0;
                    }
                }
                catch (WebException exception)
                {
                    if (exception.Message.IndexOf("404") > 0)
                    {
                        num = 4404;
                    }
                }
                try
                {
                    ((HttpWebResponse)request.GetResponse()).Close();
                }
                catch (WebException exception)
                {
                    if (exception.Status != WebExceptionStatus.ProtocolError)
                    {
                        return num;
                    }
                    if (exception.Message.IndexOf("500 ") > 0)
                    {
                        return 500;
                    }
                    if (exception.Message.IndexOf("401 ") > 0)
                    {
                        return 401;
                    }
                    if (exception.Message.IndexOf("404") > 0)
                    {
                        num = 404;
                    }
                }
            }
            return num;
        }

        //1.判断远程文件是否存在
        ///fileUrl:远程文件路径，包括IP地址以及详细的路径
        protected static bool RemoteFileExists(string fileUrl)
        {
            bool result = false;//下载结果
            WebResponse response = null;
            try
            {
                WebRequest req = WebRequest.Create(fileUrl);
                response = req.GetResponse();
                result = response == null ? false : true;
            }
            catch
            {
                result = false;
            }
            finally
            {
                if (response != null)
                {
                    response.Close();
                }
            }
            return result;
        }
        #endregion
        #region 下载远程图片到网站目录下

        /// <summary>
        /// 执行HTTP GET请求，下载资源
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="parameters">请求参数</param>
        /// <returns>HTTP响应</returns>
        public byte[] DoDownloadData(string url, IDictionary<string, string> parameters)
        {
            if (parameters != null && parameters.Count > 0)
            {
                if (url.Contains("?"))
                {
                    url = url + "&" + BuildQuery(parameters);
                }
                else
                {
                    url = url + "?" + BuildQuery(parameters);
                }
            }

            WebClient wc = new WebClient();
            wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
            wc.Encoding = Encoding.UTF8;

            return wc.DownloadData(url);
        }

        /// <summary>
        /// 下载远程图片到网站目录下
        /// </summary>
        /// <param name="url"></param>
        /// <param name="LocalPath"></param>
        /// <param name="filename"></param>
        /// <returns></returns>
        public static bool DownLoad(string url, string LocalPath, string filename)
        {
            HttpWebResponse wr = null;
            FileStream fs = null;
            Stream sIn = null;
            try
            {
                Uri u = new Uri(url);
                HttpWebRequest mRequest = (HttpWebRequest)WebRequest.Create(u);
                mRequest.Method = "GET";
                mRequest.ContentType = "application/x-www-form-urlencoded";
                wr = (HttpWebResponse)mRequest.GetResponse();
                //Debug.WriteLine("XXXX" + LocalPath +";XXXX" + filename);
                if (!Directory.Exists(LocalPath))
                    Directory.CreateDirectory(LocalPath);
                //Debug.WriteLine("XXXX" + filename);
                fs = new FileStream(LocalPath + "\\" + filename, FileMode.OpenOrCreate, FileAccess.Write);
                sIn = wr.GetResponseStream();
                long length = wr.ContentLength;
                int i = 0;
                long j = 0;
                byte[] buffer = new byte[1024];
                while ((i = sIn.Read(buffer, 0, buffer.Length)) > 0)
                {
                    j += i;
                    fs.Write(buffer, 0, i);
                }
                return true;
            }
            catch (Exception e)
            {
                // 日志
                //Debug.WriteLine(String.Format("[PMH.Managerv3][PMHAuditUsers][DAL:DownLoad]:time={0},异常信息:{1}", DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss fff"), e.Message));
                Trace.Write(String.Format("[PMH.Managerv3][PMHAuditUsers][DAL:DownLoad]:time={0},异常信息:{1}", DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss fff"), e.Message));//用于测试查看
                return false;
            }
            finally
            {
                sIn.Close();
                wr.Close();
                fs.Close();
            }

        }
        #endregion
        #region 保存远程图片
        /// <summary>
        /// 获取远程图片的数据流
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static Stream GetYCStream(string url)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            MemoryStream ms = new MemoryStream();
            return response.GetResponseStream();
        }

        /// <summary>
        /// 图片流保存为图片
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="filename"></param>
        /// <returns></returns>
        public static string SaveYCStream(Stream stream, Dictionary<string, string> filename)
        {
            Bitmap _Bitmap = (Bitmap)Bitmap.FromStream(stream);
            MemoryStream ms = new MemoryStream();
            _Bitmap.Save(ms, ImageFormat.Jpeg);
            string _sPath = filename["dirpath"].ToString();
            string _filename = filename["filename"].ToString();
            if (!Directory.Exists(_sPath))
            {
                Directory.CreateDirectory(_sPath);
            }
            using (Stream localFile = new FileStream(_sPath + _filename, FileMode.OpenOrCreate))
            {
                //ms.ToArray()转换为字节数组就是想要的图片源字节
                localFile.Write(ms.ToArray(), 0, (int)ms.Length);
            }
            return _sPath + _filename;
        }

        /// <summary>
        /// 数据流保存成文件
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="filename">文件路径+文件名</param>
        public static bool WriteFile(System.IO.Stream stream, string filename)
        {
            try
            {
                using (System.IO.StreamWriter objwrite = new System.IO.StreamWriter(filename))
                {
                    int k = 0;
                    while (k != -1)
                    {
                        k = stream.ReadByte();
                        if (k != -1)
                        {
                            objwrite.BaseStream.WriteByte((byte)k);
                        }
                    }
                }
                return true;
            }
            catch
            {
                return false;
            }
        }
        #endregion
        #region 编码，解码
        /// <summary>
        /// unicode解码
        /// </summary>
        /// <param name="match"></param>
        /// <returns></returns>
        public static string DecodeUnicode(Match match)
        {
            if (!match.Success)
            {
                return null;
            }

            char outStr = (char)int.Parse(match.Value.Remove(0, 2), System.Globalization.NumberStyles.HexNumber);
            return new string(outStr, 1);
        }

        public static string GetJsonString(object data)
        {
            JavaScriptSerializer js = new JavaScriptSerializer();
            var jsonString = js.Serialize(data);

            //解码Unicode，也可以通过设置App.Config（Web.Config）设置来做，这里只是暂时弥补一下，用到的地方不多
            MatchEvaluator evaluator = new MatchEvaluator(DecodeUnicode);
            var json = Regex.Replace(jsonString, @"\\u[0123456789abcdef]{4}", evaluator);//或：[\\u007f-\\uffff]，\对应为\u000a，但一般情况下会保持\
            return json;
        }
        #endregion
        #region 获取文件的md5值
        /// <summary>
        /// 获取文件的md5值
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static string getMd5Hash(byte[] data)
        {
            MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();
            byte[] result = md5Hasher.ComputeHash(data);
            StringBuilder sBuilder = new StringBuilder();
            for (int i = 0; i < result.Length; i++)
            {
                sBuilder.Append(result[i].ToString("x2"));
            }
            return sBuilder.ToString();
        }
        /// <summary>
        /// Hash an input string and return the hash as a 32 character hexadecimal string.  
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string getMd5Hash(string input)
        {
            //Create a new instance of the MD5CryptoServiceProvider object.  
            MD5 md5Hasher = MD5.Create();
            //Convert the input string to a byte array and compute the hash.  
            byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input));
            //Create a new Stringbuilder to collect the bytes and create a string.  
            StringBuilder sBuilder = new StringBuilder();
            //Loop through each byte of the hashed data and format each one as a hexadecimal string.  
            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }
            //Return the hexadecimal string. 
            return sBuilder.ToString();
        }
        /// <summary>
        /// 获取文件的md5值
        /// </summary>
        /// <param name="filename">文件的物理路径（如：D:\dwb\excel\AA.xls）</param>
        /// <returns></returns>
        public static string ByteArrayToHexString(string filename)
        {
            FileStream fs = new FileStream(filename, FileMode.Open);
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            md5.Initialize();
            byte[] bytes = md5.ComputeHash(fs);
            md5.Clear();
            fs.Close();
            StringBuilder sb = new StringBuilder();
            foreach (byte b in bytes)
                sb.Append(b.ToString("x2"));
            return sb.ToString();
        }
        /// <summary>
        /// 获取文件md5值
        /// </summary>
        /// <param name="fileName">传入的文件名（含路径及后缀名）</param>
        /// <returns></returns>
        private static string GetMD5HashFromFile(string fileName)
        {
            try
            {
                FileStream file = new FileStream(fileName, FileMode.Open);
                System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
                byte[] retVal = md5.ComputeHash(file);
                file.Close();

                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < retVal.Length; i++)
                {
                    sb.Append(retVal[i].ToString("x2"));
                }
                return sb.ToString();
            }
            catch (Exception ex)
            {
                throw new Exception("GetMD5HashFromFile() fail,error:" + ex.Message);
            }
        }
        /// <summary>
        /// 验证md5值
        /// </summary>
        /// <param name="strMD5"></param>
        /// <param name="checkstr">字符串</param>
        /// <returns></returns>
        public static bool ValidateMD5(string strMD5, string checkstr)
        {
            string resultstr = FormsAuthentication.HashPasswordForStoringInConfigFile(checkstr, "md5");
            return strMD5.Equals(resultstr);
        }
        /// <summary>
        /// 字符串md5加密
        /// </summary>
        /// <param name="checkstr">字符串</param>
        /// <returns></returns>
        public static string SetMD5(string checkstr)
        {
            return FormsAuthentication.HashPasswordForStoringInConfigFile(checkstr, "MD5");
        }
        #endregion
        #region 加密解密文件
        /* 加密配置文件：
         * 1.生成加密解密需要的密钥 string sSecretKey = GenerateKey();// 密钥
         * 2.加密，解密
         * **/
        /// <summary>
        /// 根据KEY生成密钥
        /// </summary>
        /// <param name="key">KEY字符串</param>
        /// <returns></returns>
        public static string GenerateKey(string key)
        {
            byte[] keys = new byte[8];
            int j = 0;
            for (int i = 0; i < keys.Length; i++)
            {
                keys[i] = Convert.ToByte(System.Text.Encoding.Unicode.GetBytes(key.Substring(j, 1))[0] - 5);
                j += 2;
            }
            byte[] keys1 = new byte[8];
            for (int i = 0; i < keys.Length; i++)
            {
                keys1[i] = keys[keys.Length - i - 1];
            }
            return ASCIIEncoding.ASCII.GetString(keys1);
        }
        /// <summary>
        /// 加密文件
        /// </summary>
        /// <param name="sInputFilename">需要加密的文件（包括路径）</param>
        /// <param name="sOutputFilename">加密后的文件（包括路径）</param>
        /// <param name="sKey">密钥</param>
        public static void EncryptFile(string sInputFilename, string sOutputFilename, string sKey)
        {
            FileStream fsInput = new FileStream(sInputFilename, FileMode.Open, FileAccess.Read);
            FileStream fsEncrypted = new FileStream(sOutputFilename, FileMode.Create, FileAccess.Write);
            DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
            DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
            DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
            ICryptoTransform desencrypt = DES.CreateEncryptor();
            CryptoStream cryptostream = new CryptoStream(fsEncrypted, desencrypt, CryptoStreamMode.Write);
            byte[] bytearrayinput = new byte[fsInput.Length];
            fsInput.Read(bytearrayinput, 0, bytearrayinput.Length);
            cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length);
            cryptostream.Close();
            fsInput.Close();
            fsEncrypted.Close();
        }
        /// <summary>
        /// 解密文件
        /// </summary>
        /// <param name="sInputFilename">需要解密的文件（包括路径）</param>
        /// <param name="sOutputFilename">解密后的文件（包括路径）</param>
        /// <param name="sKey">密钥</param>
        public static void DecryptFile(string sInputFilename, string sOutputFilename, string sKey)
        {
            DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
            //A 64 bit key and IV is required for this provider.
            //Set secret key For DES algorithm.
            DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
            //Set initialization vector.
            DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
            FileStream fsread = new FileStream(sInputFilename, FileMode.Open, FileAccess.Read);
            ICryptoTransform desdecrypt = DES.CreateDecryptor();
            CryptoStream cryptostreamDecr = new CryptoStream(fsread, desdecrypt, CryptoStreamMode.Read);
            StreamWriter fsDecrypted = new StreamWriter(sOutputFilename);
            fsDecrypted.Write(new StreamReader(cryptostreamDecr).ReadToEnd());
            fsDecrypted.Flush();
            fsDecrypted.Close();
            fsread.Close();
        }
        #endregion
    }
}
